﻿using Manon.Autofac;
using Manon.ConfigCenter.Web.ApplicationCore.Dtos.Environment;
using Manon.ConfigCenter.Web.ApplicationCore.Entities;
using Manon.ConfigCenter.Web.ApplicationCore.Interfaces;
using Manon.ConfigCenter.Web.Common;
using Manon.Core.Commons;
using Manon.Repository;
using Manon.User.Api.ApplicationCore.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Manon.ConfigCenter.Web.ApplicationCore.Services
{
    public class EnvironmentService : IEnvironmentService, ISingletonDependency
    {
        /// <summary>
        /// 获取环境变量列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<EnvironmentOutput>> GetEnvironmentListAsync()
        {
            var logger = Resolver.Resolve<ILogger<EnvironmentService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                int CurrentUserId = identityUser.UserId;

                var roleService = Resolver.Resolve<IRoleService>();

                List<int> listPermissEnvIds = await roleService.GetUserEnvIds(CurrentUserId);


                List<EnvironmentOutput> list = new List<EnvironmentOutput>();

                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();
                var reops = unitOfWork.GetRepository<Environments>();

                var result = await reops.GetAll().OrderBy(n => n.OrderIndex).ThenBy(n => n.Id).ToListAsync();
                if (result == null)
                {
                    return list;
                }

                foreach (var item in result)
                {
                    if (!(listPermissEnvIds.Contains(item.Id) || item.CreateBy == identityUser.UserId)) continue;

                    list.Add(new EnvironmentOutput()
                    {
                        Id = item.Id,
                        CreateTime = item.CreateTime,
                        EnvCode = item.EnvCode,
                        EnvName = item.EnvName,
                        IsAllowDeleted = item.IsAllowDeleted,
                        OrderIndex = item.OrderIndex,
                        Remark = item.Remark,
                        UpdateTime = item.UpdateTime
                    });
                }
                return list;


            }
            catch (Exception ex)
            {
                logger.LogError("获取环境变量列表异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 获取环境变量信息
        /// </summary>
        /// <param name="EnvId"></param>
        /// <returns></returns>
        public async Task<EnvironmentOutput> GetEnvironmentOutput(int EnvId)
        {
            var logger = Resolver.Resolve<ILogger<EnvironmentService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                int CurrentUserId = identityUser.UserId;

                var roleService = Resolver.Resolve<IRoleService>();


                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();

                var reops = unitOfWork.GetRepository<Environments>();

                var item = await reops.FindAsync(EnvId);
                if (item == null)
                {
                    return null;
                }
                List<int> listPermissEnvIds = await roleService.GetUserEnvIds(CurrentUserId);

                if (!(listPermissEnvIds.Contains(EnvId) || item.CreateBy == CurrentUserId)) return new EnvironmentOutput();


                return new EnvironmentOutput()
                {
                    Id = item.Id,
                    CreateTime = item.CreateTime,
                    EnvCode = item.EnvCode,
                    EnvName = item.EnvName,
                    IsAllowDeleted = item.IsAllowDeleted,
                    OrderIndex = item.OrderIndex,
                    Remark = item.Remark,
                    UpdateTime = item.UpdateTime
                };

            }
            catch (Exception ex)
            {
                logger.LogError("获取环境变量信息异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 保存环境
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result<EnvironmentOutput>> SaveEnvironment(SaveEnvironmentInput Input)
        {
            var logger = Resolver.Resolve<ILogger<ProjectService>>();
            try
            {
                var roleService = Resolver.Resolve<IRoleService>();
                var identityUser = Resolver.Resolve<IIdentityUser>();
                int CurrentUserId = identityUser.UserId;
                List<int> listPermissEnvIds = await roleService.GetUserEnvIds(CurrentUserId);

                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();
                var repos = unitOfWork.GetRepository<Environments>();
                Environments env = new Environments();
                if (Input.Id == 0)
                {

                    env.Id = Input.Id;
                    env.EnvCode = Input.EnvCode;
                    env.OrderIndex = Input.OrderIndex;
                    env.EnvName = Input.EnvName;
                    env.Remark = Input.Remark;
                    env.UpdateTime = DateTime.Now;
                    env.IsAllowDeleted = true;
                    env.CreateTime = DateTime.Now;
                    env.CreateBy = identityUser.UserId;
                    env.UpdateBy = identityUser.UserId;
                    await repos.InsertAsync(env);
                }
                else
                {


                    env = await repos.FindAsync(Input.Id);

                    if (!(listPermissEnvIds.Contains(Input.Id) || env.CreateBy == CurrentUserId)) return Result<EnvironmentOutput>.Failed("您没有权限操作");

                    env.Id = Input.Id;
                    env.EnvCode = Input.EnvCode;
                    env.OrderIndex = Input.OrderIndex;
                    env.EnvName = Input.EnvName;
                    env.Remark = Input.Remark;
                    env.UpdateTime = DateTime.Now;
                    env.IsAllowDeleted = true;
                    env.UpdateBy = identityUser.UserId;
                    repos.Update(env);
                }
                await unitOfWork.SaveChangesAsync();
                return Result<EnvironmentOutput>.Successed("保存成功!", new EnvironmentOutput()
                {
                    CreateTime = env.CreateTime,
                    EnvCode = env.EnvCode,
                    EnvName = env.EnvName,
                    Id = env.Id,
                    IsAllowDeleted = env.IsAllowDeleted,
                    OrderIndex = env.OrderIndex,
                    Remark = env.Remark,
                    UpdateTime = env.UpdateTime
                });
            }
            catch (Exception ex)
            {
                logger.LogError("获取api资源异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 删除环境
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public async Task<Result> DelEnvironment(int envId)
        {
            var logger = Resolver.Resolve<ILogger<ProjectService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                int CurrentUserId = identityUser.UserId;

                var roleService = Resolver.Resolve<IRoleService>();



                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();
                var repos = unitOfWork.GetRepository<Environments>();

                var env = await repos.FindAsync(envId);

                List<int> listPermissEnvIds = await roleService.GetUserEnvIds(CurrentUserId);

                if (!(listPermissEnvIds.Contains(envId) || env.CreateBy != env.CreateBy))
                {

                    return Result.Failed("您没有权限删除该数据");
                };

                repos.Delete(envId);
                await unitOfWork.SaveChangesAsync();
                return Result.Successed("删除成功!");
            }
            catch (Exception ex)
            {
                logger.LogError("删除环境异常", ex);
                throw;
            }
        }

        /// <summary>
        /// 获取环境变量简要信息列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<EnvironmentSimpleOutput>> GetEnvironmentSimpleListAsync()
        {
            var logger = Resolver.Resolve<ILogger<EnvironmentService>>();
            try
            {
                var identityUser = Resolver.Resolve<IIdentityUser>();
                int CurrentUserId = identityUser.UserId;

                var roleService = Resolver.Resolve<IRoleService>();

                List<int> listPermissEnvIds = await roleService.GetUserEnvIds(CurrentUserId);

                List<EnvironmentSimpleOutput> list = new List<EnvironmentSimpleOutput>();

                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();
                var reops = unitOfWork.GetRepository<Environments>();

                var result = await reops.GetAll().OrderBy(n => n.OrderIndex).ThenBy(n => n.Id).ToListAsync();
                if (result == null)
                {
                    return list;
                }

                foreach (var item in result)
                {
                    if (!(listPermissEnvIds.Contains(item.Id) || item.CreateBy == CurrentUserId)) continue;

                    list.Add(new EnvironmentSimpleOutput()
                    {
                        Id = item.Id.ToString(),
                        EnvCode = item.EnvCode,
                        EnvName = item.EnvName,
                    });
                }
                return list;


            }
            catch (Exception ex)
            {
                logger.LogError("获取环境变量列表异常", ex);
                throw;
            }
        }


        /// <summary>
        /// 获取所有环境变量简要信息列表 无需权限控制的
        /// </summary>
        /// <returns></returns>
        public async Task<List<EnvironmentSimpleOutput>> GetAllEnvironmentSimpleListAsync()
        {
            var logger = Resolver.Resolve<ILogger<EnvironmentService>>();
            try
            {
                List<EnvironmentSimpleOutput> list = new List<EnvironmentSimpleOutput>();

                var unitOfWork = Resolver.Resolve<IUnitOfWork<ConfigCenterDbContext>>();
                var reops = unitOfWork.GetRepository<Environments>();

                var result = await reops.GetAll().OrderBy(n => n.OrderIndex).ThenBy(n => n.Id).ToListAsync();
                if (result == null)
                {
                    return list;
                }

                foreach (var item in result)
                {
                    list.Add(new EnvironmentSimpleOutput()
                    {
                        Id = item.Id.ToString(),
                        EnvCode = item.EnvCode,
                        EnvName = item.EnvName,
                    });
                }
                return list;


            }
            catch (Exception ex)
            {
                logger.LogError("获取所有环境变量简要信息列表异常", ex);
                throw;
            }
        }
    }
}
